package com.kfyang.manualgear.daoplugin.reference;

import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.kfyang.manualgear.daoplugin.Constants;
import com.kfyang.manualgear.daoplugin.util.PsiUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class FragReference extends PsiReferenceBase<PsiElement> {

    private final String fragName;

    public FragReference(@NotNull PsiElement element, TextRange textRange, String fragName) {
        super(element, textRange);
//        key = element.getText().substring(textRange.getStartOffset(), textRange.getEndOffset());
        this.fragName = fragName;
        
    }

    @Override
    public @Nullable PsiElement resolve() {
        PsiElement element = getElement();
//        Project project = element.getProject();
//        PsiAnnotation annotation = (PsiAnnotation) AnnotationUtils.findParent(element, 3);
        PsiMethod method = (PsiMethod) PsiUtils.findParent(element, 5);

        PsiAnnotation[] annotations = method.getAnnotations();
        for (PsiAnnotation eachAnno : annotations) {
//            System.out.println(each.getQualifiedName());
            if (Constants.FRAG_ANNO.equals(eachAnno.getQualifiedName())) {
                for (PsiNameValuePair eachPair : eachAnno.getParameterList().getAttributes()) {
                    if ("id".equals(eachPair.getName())) {
                        PsiLiteralExpression literalExpression = (PsiLiteralExpression) eachPair.getValue();

                        String id = literalExpression.getText();
                        if (fragName.equals(id.substring(1, id.length() - 1)))
                            return literalExpression;
                    }
                }
            }
        }
        return null;
    }

}
